package com.tg.app.activity.device.ui.cameraview;

import static com.demo.view.TimeRuleView.MAX_TIME_VALUE;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.appbase.custom.constant.CommonConstants;
import com.demo.view.TimeRuleView;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.media.source.impl.local.DeviceStoragePlayback;
import com.tg.app.R;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.DeviceUIHelper;
import com.tg.app.playback.PlaybackMediaListener;
import com.tg.app.playback.TGPlayback;
import com.tg.app.view.ACPlayBackView;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.AVFrames;
import com.tg.data.http.entity.EventMessageBean;
import com.tg.data.http.entity.WheelData;
import com.tg.message.adapter.MessageDateAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

public abstract class PlayBackBaseFragment extends CameraBaseFragment implements PlaybackMediaListener, PlaybackRunnableHelper.RunnableListener {
    public static final String TAG = "PlayBackFragment-log";
    public static final String EXT_PLAYBACK_TYPE = "ext_playback_type";
    public static final String EXT_PLAYBACK_START = "ext_playback_start_animations";
    protected TGPlayback mTGPlayback;
    protected TimeZone mTimeZone;
    protected String mRecordDay;
    protected String mJumpEventTime;
    protected MessageDateAdapter messageDateAdapter;
    protected RecyclerView mRecyclerView;  //时间view

    protected DeviceUIHelper mDeviceUIHelper;
    protected ACPlayBackView playBackView;
    protected View centerLine;
    protected RelativeLayout playbackLayout;
    protected int mSdCardSize = -999;
    protected boolean mIsAnimationsStart;
    protected int nowTimeValue;
    protected int curTimeValue;
    protected ErrorMessageListener mErrorMessageListener;
    protected ArrayList<TimeRuleView.TimePart> recordTimes = new ArrayList<>();//event recordTimes
    protected List<EventMessageBean> eventList = new ArrayList<>();
    protected ArrayList<TimeRuleView.TimePart> timeRuleList = new ArrayList<>();//event recordTimes
    protected List<WheelData> wheelData = new ArrayList<>();
    protected LostFilePopupWindowHelper mLostFilePopupWindowHelper = new LostFilePopupWindowHelper();
    protected PlaybackRunnableHelper mPlaybackRunnableHelper = new PlaybackRunnableHelper();
    protected boolean landscape;
    protected boolean ossFailed;
    protected View mPlayerSpeedLayout;
    protected boolean isPlaybackPause;
    protected int speed = 1;
    public TGPlayback getTGPlayback() {
        return mTGPlayback;
    }
    protected MessageDateAdapter.OnMessageDateItemListener onDateItemListener;
    public void setOnDateItemListener(MessageDateAdapter.OnMessageDateItemListener onDateItemListener) {
        this.onDateItemListener = onDateItemListener;
    }
    public void setSpeed(int speed){
        this.speed = speed;
    }
    private int getIndexTime(int times){
        for (int i = recordTimes.size() - 1; i >= 0; i--) {
            TimeRuleView.TimePart timePart = recordTimes.get(i);

            if (timePart == null) continue;

            if (times < timePart.startTime){
                return -1;
            }
            if (times <= timePart.endTime){
                return i;
            }
        }
        return -1;
    }

    public int getSecondDay(long pts){
         return DateUtil.getSecondDay(pts, mTimeZone);
    }


    public boolean isJump(int startTime, int endTime){
        TGLog.d("startTime = " + startTime + ", endTime = " + endTime);
        int first = getIndexTime(startTime);
        if (first == -1){
            return false;
        }
        int end = getIndexTime(endTime);
        if (end == -1){
            return false;
        }


        if (first != end){
            if (Math.abs(first - end) == 1){
                TimeRuleView.TimePart firstData = recordTimes.get(first);
                TimeRuleView.TimePart endData = recordTimes.get(end);
                if (first > end){
                    return firstData.endTime < endData.startTime;
                }
                return endData.endTime < firstData.startTime;
            }
            return true;
        }

        return false;
    }

    public void setCarPrimaryService(){
        playBackView.setBuyCloudServiceShow();
    }



    public void setLayoutShow(boolean playBackViewShow, boolean speedLayoutShow) {
        playBackView.setVisibility(playBackViewShow ? View.VISIBLE : View.GONE);
        mPlayerSpeedLayout.setVisibility(speedLayoutShow ? View.VISIBLE : View.GONE);
    }

    private void setTextColor(List<String> list, TextView uhd) {
        if (list.get(0).equals(uhd.getText().toString())) {
            uhd.setTextColor(getResources().getColor(R.color.message_body_textcolor));
        } else {
            uhd.setTextColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.play_back_fragment, container, false);
        this.mRecyclerView = view.findViewById(R.id.rv_playback_date);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        this.mRecyclerView.setLayoutManager(linearLayoutManager);
        this.messageDateAdapter = new MessageDateAdapter(wheelData);
        this.mRecyclerView.setAdapter(this.messageDateAdapter);
        playBackView = view.findViewById(R.id.playback_view);
        if (playBackView != null) {
            playBackView.setDeviceItem(mDeviceItem);
            playBackView.setDeviceUIHelper(mDeviceUIHelper);
        }
        centerLine = view.findViewById(R.id.playback_center_line);
        playbackLayout = view.findViewById(R.id.playbackview);
        mPlayerSpeedLayout = view.findViewById(R.id.camera_live_player_speed_layout);

        setListener();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (!TextUtils.isEmpty(mJumpEventTime)) {
            mRecordDay = mJumpEventTime.substring(0, 10).trim();
            playBackView.isEventForward = true;
        } else {
            mRecordDay = DateUtil.getSDFTimeYMd(mTimeZone);
        }
        playBackView.setPlayType(getPlayType());

        boolean isScrolled = mDeviceUIHelper != null && mDeviceUIHelper.isScrolled();
        if (!DeviceHelper.hasServe(mDeviceItem) && !isScrolled && !ActivityHelper.isLocalConnect(getActivity())) {
            playBackView.setCurrentTime(MAX_TIME_VALUE, false);
        }

        initDateList();

    }

    @Override
    public void onPlaybackAudioData(AVFrames avFrame) {
        if (onICameraAVListener != null) {
            onICameraAVListener.receiveAudioData(avFrame);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getParameter();
        createTGPlayback();

    }

    private void getParameter() {
        mPlaybackRunnableHelper.setRunnableListener(this);
        if (getArguments() != null) {
            mDeviceItem = getArguments().getParcelable(CommonConstants.EXT_DEVICE_ITEM);
            assert mDeviceItem != null;
            if (mDeviceItem == null) {
                return;
            }

            mIsAnimationsStart = getArguments().getBoolean(EXT_PLAYBACK_START, false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TGLog.i(TAG, "onDestroy");
        if (mTGPlayback != null) {
            mTGPlayback.clear();
            mTGPlayback.setPlaybackMediaListener(null);
        }
    }

    public void setDeviceItem(DeviceItem deviceItem) {
        this.mDeviceItem = deviceItem;
        if (playBackView != null) {
            playBackView.setDeviceItem(deviceItem);
        }
        initTimeZone(deviceItem);
    }

    protected void setVideoNone() {
        playBackView.setSdCardVideoNone();
    }

    private void initTimeZone(DeviceItem deviceItem) {
        mTimeZone = DeviceHelper.getTimeZone(deviceItem);
    }

    @Override
    public void onResume() {
        super.onResume();
        int orientation = getResources().getConfiguration().orientation;
        configurationView(orientation);

    }

    public void setDeviceUIHelper(DeviceUIHelper deviceUIHelper) {
        mDeviceUIHelper = deviceUIHelper;
        if (playBackView != null) {
            playBackView.setDeviceUIHelper(deviceUIHelper);
        }
    }

    public int getSdCardSize() {
        return mSdCardSize;
    }


    public void setSdCardSize(int sdCardSize, boolean newData) {
        TGLog.d("sdCardSize = " + sdCardSize + ", mSdCardSize = " + mSdCardSize);
        mSdCardSize = sdCardSize;
    }

    public void setAnimationsStart(boolean animationsStart) {
        mIsAnimationsStart = animationsStart;
    }

    public void setJumpEventTime(String jumpEventTime) {
        mJumpEventTime = jumpEventTime;
    }


    @Override
    protected void configurationView(int orientation) {
        if (playBackView != null) {
            playBackView.onConfigurationChanged(orientation);
        }
        landscape = orientation == Configuration.ORIENTATION_LANDSCAPE;
        if (landscape) {
            playbackLayout.setBackgroundResource(R.color.camera_content_bg_transparent);
            showPlaybackControl(false);
        } else {
            setLayoutShow(true, false);
            playbackLayout.setBackgroundResource(R.color.play_background);
            showPlaybackControl(true);
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        configurationView(newConfig.orientation);

    }

    public String getRecordDay() {
        return mRecordDay;
    }

    public int getNowTimeValue() {
        if (playBackView == null) {
            return 0;
        }
        return nowTimeValue;
    }

    public int getDateStatus(boolean isServe, int i, int sayDays) {
        return 1;
    }

    public void setPlaybackOff() {
        timeRuleList.clear();
        recordTimes.clear();
        initDateList();
        eventList.clear();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void initDateList() {
        wheelData.clear();
        int DAY_OF_AGO = 30;
        String[] weeks = getResources().getStringArray(R.array.calendar_weeks);
        for (int i = 0; i < DAY_OF_AGO; i++) {
            WheelData data = new WheelData();
            data.status = 1;
            int weekIndex = DateUtil.getDayOffWeek(i, TimeZone.getDefault()) - 1;
            data.week = weeks[weekIndex];
            String day = DateUtil.getLastSomeDate(i, TimeZone.getDefault());
            data.date = day;
            wheelData.add(data);
        }
        messageDateAdapter.setSelectedDay(0);
        messageDateAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(0);

    }

    public void addPlayBackFooterView() {
        playBackView.addEventFooterView();
        mIsAnimationsStart = false;
    }


    public void onPlaybackVideoData(AVFrames avFrame) {
        if (onICameraAVListener != null) {
            if (avFrame.getSubType() == 0) {
                onICameraAVListener.receiveVideoData(avFrame);
            } else {
                onICameraAVListener.receiveSubVideoData(avFrame);
            }
        }
        mLostFilePopupWindowHelper.hide();
    }

    public void onMediaPlayChanged(boolean isStart) {
        if (isStart) {
            mPlaybackRunnableHelper.removeAutoScrollRunnable();
            mPlaybackRunnableHelper.removeTimeRuleViewJumpNextRunnable();
            if (mTGPlayback != null) {
                mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000 / mTGPlayback.getSpeed());
            }
        }
    }

    protected void resume() {
        if (!mIsAnimationsStart) {
            rePlayCurrentTime();//
        }
    }

    public abstract void setListener();

    public abstract int getPlayType();

    public abstract void createTGPlayback();

    public abstract void onMediaPlayUpdated(long pts);

    public abstract void onMediaCloudPlayUpdated(long pts);

    public abstract void showPlaybackControl(boolean show);

    public abstract void rePlayCurrentTime();

    public abstract void onPlaybackPause();

    public abstract void getRecordList(String rDay);
    public abstract void playBackControl(boolean pause);
    @Override
    public void onPause() {
        super.onPause();

        mPlaybackRunnableHelper.removeTimeRuleViewJumpNextRunnable();
        mPlaybackRunnableHelper.removeAutoScrollRunnable();
        TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
    }

    public interface ErrorMessageListener {
        void onNoServe();
    }

    public void stopLive() {
        TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
    }



    public void setEventList(List<DeviceStoragePlayback.Index> eventList, List<TimeRuleView.TimePart> recordParts, List<TimeRuleView.TimePart> timeParts) {
        playBackView.setEventList(eventList);
        playBackView.setTimePartList(timeParts);
        recordTimes.clear();
        recordTimes.addAll(recordParts);

    }

    protected void cloudNoneService() {
        timeRuleList.clear();
        eventList.clear();
        //playBackView.setTimePartList(timeRuleList);

        playBackView.setSimExpiredServiceShow();
    }

    protected void showSimExpiredService(){
        playBackView.showSimExpiredService();
    }

    public void setPlaybackTime(int time) {

    }

    public void setServiceInfo() {
        if (DeviceHelper.is4GDevice(mDeviceItem) && DeviceHelper.is4GExpired(mDeviceItem, true)) {
            cloudNoneService();
        }else{
            showSimExpiredService();
        }

    }
}
